<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { TClass } from '../../../../Types/education'
import BaseEchart from '../../../../components/Echart/baseEchart.vue'

/**
 * 模块名: 成绩管理
 * 代码描述:
 * 作者:mck
 * 创建时间:2025/02/14 20:25:20
 */
// 接收数据
const props = defineProps<{
	scoreManageSetting: {
		data: TClass
		visible: boolean
	}
}>()

// 当前选中的学年
const currentYear = ref('2023-2024')

// 学年列表
const academicYears = ref(['2023-2024', '2022-2023', '2021-2022'])

// 扩展成绩数据结构
const scoreList = ref([
	{
		studentId: '202100101',
		studentName: '张三',
		year: '2023-2024',
		subject1: 85,
		subject2: 92,
		subject3: 88,
		allScore: 488.3
	},
	{
		studentId: '202100102',
		studentName: '李四',
		year: '2023-2024',
		subject1: 92,
		subject2: 95,
		subject3: 90,
		allScore: 192.3
	},
	{
		studentId: '202100103',
		studentName: '王五',
		year: '2023-2024',
		subject1: 78,
		subject2: 82,
		subject3: 75,
		allScore: 478.3
	},
	{
		studentId: '202100104',
		studentName: '赵六',
		year: '2023-2024',
		subject1: 55,
		subject2: 68,
		subject3: 72,
		allScore: 565.0
	},
	{
		studentId: '202100105',
		studentName: '钱七',
		year: '2023-2024',
		subject1: 45,
		subject2: 58,
		subject3: 52,
		allScore: 185
	},
	// 2022-2023学年数据
	{
		studentId: '202200101',
		studentName: '孙八',
		year: '2022-2023',
		subject1: 88,
		subject2: 85,
		subject3: 92,
		allScore: 288.3
	},
	{
		studentId: '202200102',
		studentName: '周九',
		year: '2022-2023',
		subject1: 95,
		subject2: 91,
		subject3: 94,
		allScore: 493.3
	},
	{
		studentId: '202200103',
		studentName: '吴十',
		year: '2022-2023',
		subject1: 72,
		subject2: 75,
		subject3: 78,
		allScore: 175.0
	}
])

// 表格列配置
const columns = [
	{ prop: 'studentId', label: '学号', width: '120' },
	{ prop: 'studentName', label: '姓名', width: '100' },
	{ prop: 'subject1', label: '科目1', width: '100' },
	{ prop: 'subject2', label: '科目2', width: '100' },
	{ prop: 'subject3', label: '科目3', width: '100' },
	{ prop: 'allScore', label: '总分', width: '100' }
]

/**
 * 模块名: 数据处理
 * 代码描述:
 * 作者:mck
 * 创建时间:2025/02/14 23:03:57
 */
// 扩展统计数据计算
const statistics = computed(() => {
	const currentScores = scoreList.value.filter((score) => score.year === currentYear.value)
	return {
		// 班级成绩统计
		classStats: {
			totalScore: {
				value: 85.6, // 班级总分
				rank: 3, // 学院排名
				total: 15 // 学院总班级数
			},
			excellentRate: {
				value: 25, // 优秀率
				rank: 5, // 学院排名
				academyAvg: 22 // 学院平均优秀率
			},
			passRate: {
				value: 85, // 及格率
				rank: 8, // 年级排名
				total: 32, // 年级总班级数
				gradeAvg: 82 // 年级平均及格率
			},
			failRate: {
				value: 15, // 挂科率
				academyAvg: 18 // 学院平均挂科率
			},
			violationRate: {
				value: 0, // 违纪率
				total: 0 // 违纪人数
			}
		}
	}
})

/**
 * 模块名: 图表配置
 * 代码描述:
 * 作者:mck
 * 创建时间:2025/02/14 22:21:38
 */
// 计算图表数据
const chartOption = computed(() => {
	const currentScores = scoreList.value.filter((score) => score.year === currentYear.value)

	// 科目名称映射关系
	const subjectMapping = {
		科目1: 'subject1',
		科目2: 'subject2',
		科目3: 'subject3'
	}

	const subjects = ['科目1', '科目2', '科目3']

	// 重新定义分数段
	const scoreRanges = [
		{ name: '未及格', min: 0, max: 49 },
		{ name: '接近及格', min: 50, max: 59 },
		{ name: '及格', min: 60, max: 79 },
		{ name: '优秀', min: 80, max: 100 }
	]

	// 计算每个分数段的统计数据
	const statistics = scoreRanges.map((range) => {
		const subjectStats = subjects.map((subject) => {
			const propertyName = subjectMapping[subject as keyof typeof subjectMapping]
			const scores = currentScores.map((item) => item[propertyName as keyof typeof item] as number)
			const count = scores.filter((score) => score >= range.min && score <= range.max).length
			const total = scores.length
			return {
				count,
				total,
				rate: total > 0 ? Math.round((count / total) * 100) : 0
			}
		})
		return {
			range,
			stats: subjectStats
		}
	})

	return {
		title: {
			text: '各科目分数段分布'
		},
		tooltip: {
			trigger: 'axis' as const,
			axisPointer: { type: 'shadow' as const },
			formatter: (params: any) => {
				const rangeIndex = params[0].dataIndex
				const range = scoreRanges[rangeIndex]
				const totalStudents = statistics[rangeIndex].stats[0].total
				let result = `${range.name} (${range.min}-${range.max}分)<br/>`
				result += `总人数：${totalStudents}人<br/>`
				params.forEach((param: any) => {
					const subjectStats = statistics[rangeIndex].stats[param.seriesIndex]
					result += `${param.seriesName}：${subjectStats.count}人 (${subjectStats.rate}%)<br/>`
				})
				return result
			}
		},
		legend: {
			data: subjects,
			selected: subjects.reduce((acc, subject) => ({ ...acc, [subject]: true }), {})
		},
		grid: {
			top: '60px',
			bottom: '40px',
			left: '60px',
			right: '60px',
			containLabel: true
		},
		xAxis: {
			type: 'category' as const,
			data: scoreRanges.map((range) => `${range.name}\n(${range.min}-${range.max}分)`),
			axisLabel: {
				interval: 0,
				lineHeight: 16
			}
		},
		yAxis: {
			type: 'value' as const,
			name: '人数'
		},
		series: subjects.map((subject, index) => ({
			name: subject,
			type: 'bar' as const,
			barMaxWidth: 30,
			barGap: '20%',
			emphasis: {
				focus: 'series' as const
			},
			label: {
				show: true,
				position: 'top' as const
			},
			itemStyle: {
				color: [
					'#409EFF', // 科目1蓝色
					'#67C23A', // 科目2绿色
					'#E6A23C' // 科目3橙色
				][index]
			},
			data: statistics.map((item) => item.stats[index].count)
		}))
	}
})

// 图表样式
const chartStyle = {
	width: '100%',
	height: '400px'
}

// 导出成绩
const handleExport = () => {
	// 实现导出成绩的逻辑
	ElMessage.success('导出成功')
}

// 返回班级管理
const emit = defineEmits(['back'])
const handleBack = () => {
	emit('back')
}

/**
 * 模块名: 数据处理
 * 代码描述:
 * 作者:mck
 * 创建时间:2025/02/14 21:22:08
 */
// 保持数据响应
const scoreManageSetting = computed(() => props.scoreManageSetting)

// 格式化班级名称
const formatClassName = (className: string | undefined) => {
	if (!className) return ''
	return className.includes('班') ? className : className + '班'
}

// 根据分数设置样式类名
const getScoreClass = (score: number) => {
	if (score >= 100) return 'score-all'
	if (score >= 80) return 'score-good'
	if (score >= 60) return 'score-medium'
	if (score >= 50) return 'score-pass'
	if (score >= 40) return 'score-fail'
	return 'score-fail'
}
</script>

<template>
	<div class="score-manage">
		<el-card shadow="hover">
			<!-- 导航栏 -->
			<template #header>
				<div class="card-header">
					<div class="left-section">
						<el-button :icon="ArrowLeft" type="primary" @click="handleBack">返回</el-button>
						<el-divider direction="vertical" />
						<div class="class-info" v-show="scoreManageSetting.data">
							<span>{{ scoreManageSetting.data.academy }}</span>
							<el-divider direction="vertical" />
							<span>{{ scoreManageSetting.data.major }}</span>
							<el-divider direction="vertical" />
							<span>{{ scoreManageSetting.data.grade }}</span>
							<el-divider direction="vertical" />
							<span>{{ formatClassName(String(scoreManageSetting.data.classname)) }}</span>
						</div>
					</div>
					<div class="header-operations">
						<el-button @click="handleExport">导出成绩</el-button>
					</div>
				</div>
			</template>

			<!-- 顶部操作区域 -->
			<div class="operation-area">
				<div class="filter-section">
					<div class="year-selector">
						<span class="label">学年：</span>
						<el-select v-model="currentYear" size="small" class="year-select">
							<el-option v-for="year in academicYears" :key="year" :label="year" :value="year" />
						</el-select>
					</div>
				</div>
				<div class="statistics-section">
					<div class="stat-group">
						<div class="stat-item">
							<div class="main-value">
								<span class="label">总分第一</span>
								<span class="value highlight">{{ statistics.classStats.totalScore.value }}分</span>
							</div>
							<div class="sub-value">
								<span class="rank">
									年级排名：第{{ statistics.classStats.totalScore.rank }}名
								</span>
							</div>
						</div>
					</div>

					<el-divider direction="vertical" />

					<div class="stat-group">
						<div class="stat-item">
							<div class="main-value">
								<span class="label">
									<el-tooltip effect="dark" content="每科优秀率++ / 科目数" placement="top">
										优秀率
									</el-tooltip>
								</span>
								<span class="value">{{ statistics.classStats.excellentRate.value }}%</span>
							</div>
							<div class="sub-value">
								<span class="rank">
									年级排名：第{{ statistics.classStats.excellentRate.rank }}名
								</span>
							</div>
						</div>
					</div>

					<el-divider direction="vertical" />

					<div class="stat-group">
						<div class="stat-item">
							<div class="main-value">
								<span class="label">
									<el-tooltip effect="dark" content="每科及格率++ / 科目数" placement="top">
										及格率
									</el-tooltip>
								</span>
								<span class="value">{{ statistics.classStats.passRate.value }}%</span>
							</div>
							<div class="sub-value">
								<span class="rank"> 年级排名：第{{ statistics.classStats.passRate.rank }}名 </span>
							</div>
						</div>
					</div>

					<el-divider direction="vertical" />

					<div class="stat-group">
						<div class="stat-item">
							<div class="main-value">
								<span class="label">违纪情况 </span>
								<span class="error">{{ statistics.classStats.violationRate.total }}</span>
							</div>
							<div class="sub-value">
								<span class="warning"
									>年级排名：第{{ statistics.classStats.violationRate.total }}名
								</span>
							</div>
						</div>
					</div>
				</div>
			</div>

			<!-- 成绩分布图表 -->
			<div class="chart-container">
				<BaseEchart :option="chartOption" :style="chartStyle" />
			</div>

			<!-- 成绩表格 -->
			<el-table
				:data="scoreList.filter((score) => score.year === currentYear)"
				:columns="columns"
				stripe
				border
				class="score-table"
			>
				<el-table-column v-for="col in columns" :key="col.prop" v-bind="col" align="center">
					<template
						#default="{ row }"
						v-if="['subject1', 'subject2', 'subject3', 'allScore'].includes(col.prop)"
					>
						<span :class="getScoreClass(row[col.prop])">{{ row[col.prop] }}</span>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
	</div>
</template>

<style scoped lang="scss">
.score-manage {
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.left-section {
			display: flex;
			align-items: center;
			gap: 5px;
		}

		.class-info {
			font-size: 14px;
			color: var(--el-text-color-regular);
			display: flex;
			align-items: center;
			gap: 10px;
		}
	}

	.operation-area {
		display: flex;
		flex-direction: column;
		gap: 15px;
		margin-bottom: 20px;
		padding: 15px;
		background-color: var(--el-fill-color-lighter);
		border-radius: 4px;

		.filter-section {
			.year-selector {
				display: flex;
				align-items: center;
				gap: 10px;

				.label {
					font-size: 14px;
					color: var(--el-text-color-regular);
				}

				.year-select {
					width: 120px;
				}
			}
		}

		.statistics-section {
			display: flex;
			align-items: flex-start;
			margin-top: 10px;
			gap: 15px;

			.stat-group {
				min-width: 150px;

				.stat-item {
					display: flex;
					flex-direction: column;
					gap: 8px;

					.main-value {
						display: flex;
						align-items: center;
						gap: 8px;

						.label {
							font-size: 14px;
							color: var(--el-text-color-regular);
						}

						.value {
							font-size: 16px;
							font-weight: bold;
							color: var(--el-color-primary);

							&.highlight {
								color: #409eff;
								font-size: 18px;
							}
						}

						.error {
							color: #f20808;
						}
					}

					.sub-value {
						display: flex;
						flex-direction: column;
						gap: 4px;

						.rank,
						.warning {
							font-size: 13px;
							color: var(--el-text-color-secondary);
						}

						.warning {
							color: #e6a23c;
						}
					}
				}
			}
		}
	}

	.chart-container {
		height: 400px;
		margin-bottom: 20px;
	}

	.score-table {
		:deep(.el-table__header) {
			background-color: var(--el-fill-color-light);
			font-weight: bold;
		}

		.score-all {
			color: #be0bb5;
			font-weight: bold;
		}

		.score-good {
			color: #2169b1;
			font-weight: bold;
		}

		.score-medium {
			color: #067534;
		}

		.score-pass {
			color: #909399;
		}

		.score-fail {
			color: #f56c6c;
			font-weight: bold;
		}
	}
}
</style>
